package net.gazhi.delonix.core.init;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 初始化系统数据
 * 
 * @author Jeffrey Lin
 */
@Controller
@RequestMapping("/init")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class InitController {

	private boolean initialized = false;

	@Value("${initController.repeatable}")
	private boolean repeatable = false;

	@Autowired
	private InitExecuter initExecuter;

	@RequestMapping
	public void init(HttpServletResponse response) throws IOException {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.append("<h3><a href=\"./\">Back</a></h3>");
		if (this.repeatable || !this.initialized) {
			writer.append("<div>").append(fmt.format(Calendar.getInstance().getTime())).append(" Initialization started.</div>");
			initExecuter.execute();
			writer.append("<div>").append(fmt.format(Calendar.getInstance().getTime())).append(" Initialization finished.</div>");
			initialized = true;
		} else {
			writer.append("<div>You need to restart the application to execute initialization.</div>");
		}
	}

}
